﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.Common;
using ZK.Common.Log4;
using ZK.HardWareSDK;
using ZK.InterfaceServer;

namespace ZK.HardWareBLL
{
    /// <summary>
    /// 摄像头帮助类-非静态类
    /// </summary>
    public class CameraBLL
    {
        #region 属性
        //public  delegate void SetCarNum(string carNum);
        //public static SetCarNum EventSetCarNum;
        private Int32 m_lAlarmHandle;
        private ReBaseModel reBaseModel = new ReBaseModel() { Msg = "", res = true };
        private Int32 m_lUserID = -1;//用户id
        private uint iLastErr = 0;//错误代码
        private string str = "";//错误信息
        private Int32 m_lRealHandle = -1;//预览状态
        private bool m_bInitSDK = false;//初始化摄像头状态
        private int mlChannel = 0;
        /// <summary>
        /// 车牌识别一体机图片从这里取 车牌识别的图片（已经上传）
        /// </summary>
        public string CPSBPicture = "";
        private delegate void ChangedHandler_ReadedTransInfo(TransBasicInfo model, EventArgs e);//带参委托
        private static event ChangedHandler_ReadedTransInfo Change_ReadedTransInfo;//委托事件

        private delegate void ChangedHandler_ReadedTare(decimal tareQuantity, EventArgs e);
        private static event ChangedHandler_ReadedTare Change_ReadedTare;

        private delegate void ChangedHandler_ReadedRealTare(decimal realTare, EventArgs e);
        private static event ChangedHandler_ReadedRealTare Change_ReadedRealTare;

        private delegate void ChangedHandler_ReadedRealGrossWeight(decimal realGrossWeight, EventArgs e);
        private static event ChangedHandler_ReadedRealGrossWeight Change_ReadedRealGrossWeight;


        //private readonly List<InfraredGrating.InfraredGrating> _infraredGratings;



        int iListenHandle;//监听状态
        private CameraSdk.MSGCallBack m_falarmData = null;

        private static TransBasicInfo transInfo = null;
        private static TransBasicInfo TransInfo
        {
            get
            {
                return transInfo;
            }
            set
            {
                transInfo = value;
                Change_ReadedTransInfo?.Invoke(transInfo, null);
            }
        }
        public CameraModel cameraModel
        {
            get; set;
        }


        private static decimal tareQuantity = 0;
        private static decimal TareQuantity
        {
            get
            {
                return tareQuantity;
            }
            set
            {
                tareQuantity = value;
                Change_ReadedTare?.Invoke(tareQuantity, null);
            }
        }
        /// <summary>
        /// 摄像头顺序 Q 前 H 后
        /// </summary>
        public string CameraIp = "";

        #endregion

        //public void GetCameraInfo() {
        //    CameraSdk.NET_DVR_GET_WORK_STATUS
        //}

        /// <summary>
        /// 摄像头顺序（1是对外的，2是对地磅的。）
        /// </summary>
        /// <param name="num"></param>
        public CameraBLL(CameraModel cameraModel)
        {
            this.cameraModel = cameraModel;
            TestConnect.CheckDeviceStatus(cameraModel.Ip, cameraModel.Name);

        }

        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        public ReBaseModel Init()
        {
            m_bInitSDK = CameraSdk.NET_DVR_Init();
            if (m_bInitSDK == false)
            {
                reBaseModel.Msg = "NET_DVR_Init error!";
                reBaseModel.res = false;
            }
            else
            {
                //保存SDK日志 To save the SDK log
                CameraSdk.NET_DVR_SetLogToFile(3, "D:\\SdkLog\\", true);
                //设置报警回调函数
                m_falarmData = new CameraSdk.MSGCallBack(MsgCallback);
                CameraSdk.NET_DVR_SetDVRMessageCallBack_V30(m_falarmData, IntPtr.Zero);
            }
            return reBaseModel;
        }
        #endregion

        public string UpLoadFile(bool preview = true)
        {
            string guid = Guid.NewGuid().ToString();
            ReBaseModel reBaseModel = GetPucture(guid, preview);//抓图
            if (!reBaseModel.res)
            {
                Common.Log4.LogManage.WriteErr(cameraModel.Ip+" 抓图失败");
                return null;
            }
            string filePathS = ImgHelper.CompressImg(sFile: reBaseModel.Msg);//压缩图片
            if (string.IsNullOrWhiteSpace(filePathS))
            {
                Common.Log4.LogManage.WriteErr(cameraModel.Ip + "压缩图片失败");
                return null;
            }
            string errStr;
            string pictureId = FileUpload.HttpUploadFile(filePathS, out errStr);//上传图片 到服务器
            if (!string.IsNullOrWhiteSpace(errStr))
            {
                Common.Log4.LogManage.WriteErr(cameraModel.Ip+"上传图片失败"+errStr);
                return null;
            }
            return pictureId;

        }

        #region 设置警报的回调函数
        /// <summary>
        /// 设置警报的回调函数
        /// </summary>
        /// <param name="lCommand"></param>
        /// <param name="pAlarmer"></param>
        /// <param name="pAlarmInfo"></param>
        /// <param name="dwBufLen"></param>
        /// <param name="pUser"></param>
        public void MsgCallback(int lCommand, ref CameraSdk.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            //通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
            AlarmMessageHandle(lCommand, ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
        }
        #endregion

        #region 通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
        /// <summary>
        /// 通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
        /// </summary>
        /// <param name="lCommand"></param>
        /// <param name="pAlarmer"></param>
        /// <param name="pAlarmInfo"></param>
        /// <param name="dwBufLen"></param>
        /// <param name="pUser"></param>
        public void AlarmMessageHandle(int lCommand, ref CameraSdk.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo,
           uint dwBufLen, IntPtr pUser)
        {
            //通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
            switch (lCommand)
            {
                //case CameraSdk.COMM_ALARM: //(DS-8000老设备)移动侦测、视频丢失、遮挡、IO信号量等报警信息
                //    ProcessCommAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
                //case CameraSdk.COMM_ALARM_V30: //移动侦测、视频丢失、遮挡、IO信号量等报警信息
                //    ProcessCommAlarm_V30(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
                //case CameraSdk.COMM_ALARM_RULE: //进出区域、入侵、徘徊、人员聚集等行为分析报警信息
                //    ProcessCommAlarm_RULE(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
                //case CameraSdk.COMM_UPLOAD_PLATE_RESULT: //交通抓拍结果上传(老报警信息类型)
                //    ProcessCommAlarm_Plate(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
                case CameraSdk.COMM_ITS_PLATE_RESULT: //交通抓拍结果上传(新报警信息类型)
                    ProcessCommAlarm_ITSPlate(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                //case CameraSdk.COMM_ALARM_PDC: //客流量统计报警信息
                //    ProcessCommAlarm_PDC(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
                //case CameraSdk.COMM_ITS_PARK_VEHICLE: //客流量统计报警信息
                //    ProcessCommAlarm_PARK(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
                //case CameraSdk.COMM_DIAGNOSIS_UPLOAD: //VQD报警信息
                //    ProcessCommAlarm_VQD(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
                //case CameraSdk.COMM_UPLOAD_FACESNAP_RESULT: //人脸抓拍结果信息
                //    ProcessCommAlarm_FaceSnap(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
                //case CameraSdk.COMM_SNAP_MATCH_ALARM: //人脸比对结果信息
                //    ProcessCommAlarm_FaceMatch(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
                //case CameraSdk.COMM_ALARMHOST_CID_ALARM: //报警主机CID报警上传
                //    ProcessCommAlarm_CIDAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
                default:
                    {
                        //报警设备IP地址
                        var strIp = pAlarmer.sDeviceIP;

                        //报警信息类型
                        var stringAlarm = "报警上传，信息类型：" + lCommand;

                        // ReceiveAlarm?.Invoke(DateTime.Now, strIp, stringAlarm);
                    }
                    break;
            }
        }
        #endregion

        #region 警告分类

        #region 交通抓拍结果上传(新报警信息类型)
        /// <summary>
        /// 交通抓拍结果上传(新报警信息类型)
        /// </summary>
        /// <param name="pAlarmer"></param>
        /// <param name="pAlarmInfo"></param>
        /// <param name="dwBufLen"></param>
        /// <param name="pUser"></param>
        private void ProcessCommAlarm_ITSPlate(ref CameraSdk.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen,
         IntPtr pUser)
        {
            var struItsPlateResult =
                (CameraSdk.NET_ITS_PLATE_RESULT)Marshal.PtrToStructure(pAlarmInfo,
                    typeof(CameraSdk.NET_ITS_PLATE_RESULT));

            //报警设备IP地址
            // var strIp = pAlarmer.sDeviceIP;

            ////抓拍时间：年月日时分秒
            //var strTimeYear = $"{struItsPlateResult.struSnapFirstPicTime.wYear:D4}" +
            //                  $"{struItsPlateResult.struSnapFirstPicTime.byMonth:D2}" +
            //                  $"{struItsPlateResult.struSnapFirstPicTime.byDay:D2}" + " "
            //                  + $"{struItsPlateResult.struSnapFirstPicTime.byHour:D2}" + ":"
            //                  + $"{struItsPlateResult.struSnapFirstPicTime.byMinute:D2}" + ":"
            //                  + $"{struItsPlateResult.struSnapFirstPicTime.bySecond:D2}" + ":"
            //                  + $"{struItsPlateResult.struSnapFirstPicTime.wMilliSec:D3}";

            //car number (车牌号)
            var stringPlateLicense = Encoding.GetEncoding("GBK").GetString(struItsPlateResult.struPlateInfo.sLicense).TrimEnd('\0').Substring(1);
            //    .TrimEnd('\0');
            //if (!string.IsNullOrEmpty(stringPlateLicense))
            //{
            //    stringPlateLicense = stringPlateLicense.Substring(1);
            //}
            //var stringAlarm = "抓拍上传，" + "车牌：" + stringPlateLicense + "，车辆序号：" +
            //                  struItsPlateResult.struVehicleInfo.dwIndex;

            //if (stringPlateLicense.Length < 7)
            //{
            //    return;
            //}
            // LogHelper.LogInfo("车牌识别一体机识别到的车牌为:" + stringPlateLicense);

            //ReceiveAlarm?.Invoke(DateTime.Now, strIp, stringAlarm);

            #region 每次识别到车牌了，去文件夹中删除七天前的抓拍图片

            Task.Factory.StartNew(() =>
            {
                try
                {
                    string filePath = RouteHelper.PicturePath;
                    if (Directory.Exists(filePath))
                    {
                        var directories = Directory.GetDirectories(filePath);
                        foreach (var item in directories)
                        {
                            var info = new DirectoryInfo(item);
                            if (info.Exists && (info.Attributes & FileAttributes.Directory) != 0 &&
                                info.CreationTime < DateTime.Now.AddDays(-7))
                                Directory.Delete(item, true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Common.Log4.LogManage.WriteErr(ex.ToString());
                }
                //删除多余日志
                Common.Log4.LogManage.DelLogs();
            });
            #endregion

            //保存抓拍图片 如果需要车牌识别一体机的图片。。。
            //CPSBPicture =  UpLoadFile();
            //Common.Log4.LogManage.WriteDebug(CPSBPicture);

            //var strDate = $"{struItsPlateResult.struSnapFirstPicTime.wYear:D4}" +
            //              $"{struItsPlateResult.struSnapFirstPicTime.byMonth:D2}" +
            //              $"{struItsPlateResult.struSnapFirstPicTime.byDay:D2}";
            //var strDateTime = $"{strDate}" +
            //                  $"{struItsPlateResult.struSnapFirstPicTime.byHour:D2}" +
            //                  $"{struItsPlateResult.struSnapFirstPicTime.byMinute:D2}" +
            //                  $"{struItsPlateResult.struSnapFirstPicTime.bySecond:D2}" +
            //                  $"{struItsPlateResult.struSnapFirstPicTime.wMilliSec:D3}";
            //var grabbedImgPath = string.Empty;
            //var carNumberImgPath = string.Empty;
            //var caremaId = 0;
            //string FileName, realPath;
            //string fileName = Guid.NewGuid().ToString();
            //图片保存路径和文件名 the path and file name to save
            //FileName = fileName + ".bmp";
            //string timePath = DateTime.Now.ToString("yyyy-MM-dd");
            //realPath = filePath + "\\" + timePath;
            //if (!Directory.Exists(realPath))
            //{
            //    Directory.CreateDirectory(realPath);
            //}
            //realPath += "\\" + FileName;
            //for (var i = 0; i < struItsPlateResult.dwPicNum; i++)
            //    if (struItsPlateResult.struPicInfo[i].dwDataLen != 0)
            //    {
            //        //var fileName = strDateTime + "_" + (string.IsNullOrEmpty(stringPlateLicense) ? "null" : stringPlateLicense) +
            //        //        "_ITS_UserID_[" + pAlarmer.lUserID + "]_Pictype_" +
            //        //        struItsPlateResult.struPicInfo[i].byType + "_Num" + (i + 1) + ".jpg";
            //        //caremaId = pAlarmer.lUserID;
            //        //var fileName = strDateTime + "_" + (string.IsNullOrEmpty(stringPlateLicense) ? "null" : stringPlateLicense) +
            //        //        "_Pictype" + struItsPlateResult.struPicInfo[i].byType + "_Num" + (i + 1) + ".jpg";
            //        //var saveDirectory = Path.Combine(baseDirectory, strDate);
            //        //if (!Directory.Exists(saveDirectory))
            //        //    Directory.CreateDirectory(saveDirectory);
            //        //var path = Path.Combine(saveDirectory, fileName);
            //        var fs = new FileStream(realPath, FileMode.Create);
            //        var iLen = (int)struItsPlateResult.struPicInfo[i].dwDataLen;
            //        var by = new byte[iLen];
            //        Marshal.Copy(struItsPlateResult.struPicInfo[i].pBuffer, by, 0, iLen);
            //        fs.Write(by, 0, iLen);
            //        fs.Close();
            //        //if (i == 0)
            //        //    grabbedImgPath = path;
            //        //if (i == 1)
            //        //    carNumberImgPath = path;
            //    }



            if (!string.IsNullOrEmpty(stringPlateLicense) && stringPlateLicense != "无车牌" && stringPlateLicense != "车牌")
            {
                Common.Log4.LogManage.WriteInfo("摄像头获取到车牌，并触发委托" + stringPlateLicense);
                DelegateHelper.CameraGetCarNumEvent?.Invoke(stringPlateLicense, pAlarmer.sDeviceIP);
            }


        }
        #endregion

        #endregion

        #region 登录
        /// <summary>
        /// 摄像机登录
        /// </summary>
        /// <returns></returns>
        public ReBaseModel Login()
        {
            if (m_lUserID < 0)
            {
                //var cameraScalesM = MyCustomConfig.cameraScales;
                CameraSdk.NET_DVR_DEVICEINFO_V30 DeviceInfo = new CameraSdk.NET_DVR_DEVICEINFO_V30();
                ///登录设备 
                m_lUserID = CameraSdk.NET_DVR_Login_V30(cameraModel.Ip, cameraModel.Port, cameraModel.UserName, cameraModel.PassWord, ref DeviceInfo);
                if (m_lUserID < 0)
                {
                    iLastErr = CameraSdk.NET_DVR_GetLastError();
                    str = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败，输出错误号
                    reBaseModel.Msg = str;
                    reBaseModel.res = false;
                    Common.Log4.LogManage.WriteErr(str);
                }
            }
            return reBaseModel;

        }
        /// <summary>
        /// 登录（传摄像头ip）
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public ReBaseModel Login(string ip)
        {
            if (m_lUserID < 0)
            {

                CameraSdk.NET_DVR_DEVICEINFO_V30 DeviceInfo = new CameraSdk.NET_DVR_DEVICEINFO_V30();
                ///登录设备 
                m_lUserID = CameraSdk.NET_DVR_Login_V30(cameraModel.Ip, cameraModel.Port, cameraModel.UserName, cameraModel.PassWord, ref DeviceInfo);
                if (m_lUserID < 0)
                {
                    iLastErr = CameraSdk.NET_DVR_GetLastError();
                    str = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败，输出错误号
                    reBaseModel.Msg = str;
                    reBaseModel.res = false;
                }
            }
            return reBaseModel;

        }
        #endregion

        #region open the camara listen (打开摄像头监听)
        /// <summary>
        /// open the camara listen (打开摄像头监听)
        /// </summary>
        /// <param name="localIp"></param>
        /// <param name="localPort"></param>
        /// <returns></returns>
        private bool StartListen()
        {
            try
            {
                string sLocalIp = "127.0.0.1";
                ushort wLocalPort = 7200;

                if (m_falarmData == null)
                {
                    m_falarmData = MsgCallback;
                }

                iListenHandle = CameraSdk.NET_DVR_StartListen_V30(sLocalIp, wLocalPort, m_falarmData, IntPtr.Zero);
                if (iListenHandle < 0)
                {
                    var lastErr = CameraSdk.NET_DVR_GetLastError();
                    var strErr = "ip " + this.cameraModel.Ip + " 启动监听失败，错误号：" + lastErr; //启动监听失败，输出错误号
                    LogManage.WriteErr(strErr);
                    return false;
                }
                else
                {
                    // LogHelper.LogInfo("成功启动监听！");
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManage.WriteErr("摄像头启动监听 " + ex.ToString());
                return true;
            }
        }
        #endregion

        #region set Alarm  (布放)
        /// <summary>
        /// set Alarm  (布放)
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private bool SetAlarm(int userId)
        {
            var struAlarmParam = new CameraSdk.NET_DVR_SETUPALARM_PARAM();
            struAlarmParam.dwSize = (uint)Marshal.SizeOf(struAlarmParam);
            struAlarmParam.byLevel = 1; //0- 一级布防,1- 二级布防
            struAlarmParam.byAlarmInfoType = 1;//智能交通设备有效，新报警信息类型

            m_lAlarmHandle = CameraSdk.NET_DVR_SetupAlarmChan_V41(userId, ref struAlarmParam);
            if (m_lAlarmHandle < 0)
            {
                var lastErr = CameraSdk.NET_DVR_GetLastError();
                var strErr = "布防失败，错误号：" + lastErr; //布防失败，输出错误号
                LogManage.WriteErr(strErr);
                return false;
            }
            else
            {
                //LogHelper.LogInfo(@"布防成功");
                return true;
            }
        }
        #endregion

        #region 打开摄像头
        /// <summary>
        /// 打开摄像机
        /// </summary>
        /// <returns></returns>
        public ReBaseModel OpenorClose(object obj = null)
        {
            PictureBox picVideo = obj as PictureBox;
            if (m_lRealHandle < 0)
            {
                ///摄像头信息
                CameraSdk.NET_DVR_PREVIEWINFO lpPreviewInfo = new CameraSdk.NET_DVR_PREVIEWINFO();
                if (obj != null)
                    lpPreviewInfo.hPlayWnd = picVideo.Handle;//预览窗口
                // lpPreviewInfo.hPlayWnd = picVideo.Handle;//预览窗口
                lpPreviewInfo.lChannel = 1; //Int16.Parse(textBoxChannel.Text);//预te览的设备通道
                lpPreviewInfo.dwStreamType = 1;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
                lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
                lpPreviewInfo.bBlocked = true; //0- 非阻塞取流，1- 阻塞取流
                lpPreviewInfo.dwDisplayBufNum = 1; //播放库播放缓冲区最大缓冲帧数
                lpPreviewInfo.byProtoType = 0;
                lpPreviewInfo.byPreviewMode = 0;

                CameraSdk.REALDATACALLBACK RealData = new CameraSdk.REALDATACALLBACK(RealDataCallBack);//预览实时流回调函数
                IntPtr pUser = new IntPtr();//用户数据

                ///打开预览 
                m_lRealHandle = CameraSdk.NET_DVR_RealPlay_V40(m_lUserID, ref lpPreviewInfo, null, pUser);
                if (m_lRealHandle < 0)
                {
                    iLastErr = CameraSdk.NET_DVR_GetLastError();
                    str = "NET_DVR_RealPlay_V40 failed, error code= " + iLastErr; //预览失败，输出错误号
                    reBaseModel.Msg = str;
                    reBaseModel.res = false;
                    Common.Log4.LogManage.WriteErr(str);
                }
                if (SetAlarm(m_lUserID))
                {
                    StartListen();
                }

            }
            else
            {
                ///停止预览
                if (!CameraSdk.NET_DVR_StopRealPlay(m_lRealHandle))
                {
                    iLastErr = CameraSdk.NET_DVR_GetLastError();
                    str = "NET_DVR_StopRealPlay failed, error code= " + iLastErr;
                    reBaseModel.Msg = str;
                    reBaseModel.res = false;
                }
                m_lRealHandle = -1;
            }
            return reBaseModel;
        }



        #endregion

        #region 抓图
        /// <summary>
        /// 抓图
        /// </summary>
        /// <param name="fileName">保存文件的文件名字（一般传随机码作为名称）</param>
        /// <returns></returns>
        public ReBaseModel GetPucture(string fileName, bool preview = true)
        {
            reBaseModel = new ReBaseModel() { Msg = "", res = true };
            string FileName, realPath;
            //图片保存路径和文件名 the path and file name to save
            FileName = fileName + ".bmp";
            string filePath = RouteHelper.PicturePath;
            string timePath = DateTime.Now.ToString("yyyy-MM-dd");
            realPath = filePath + "\\" + timePath;
            if (!Directory.Exists(realPath))
            {
                Directory.CreateDirectory(realPath);
            }
            realPath += "\\" + FileName;
            //BMP抓图 Capture a BMP picture
            if (preview)
            {
                if (!CameraSdk.NET_DVR_CapturePicture(m_lRealHandle, realPath))
                {
                    iLastErr = CameraSdk.NET_DVR_GetLastError();
                    str = "NET_DVR_CapturePicture failed, error code= " + iLastErr;
                    reBaseModel.Msg = str;
                    reBaseModel.res = false;
                    Common.Log4.LogManage.WriteErr("摄像头抓图失败 ip:" + this.cameraModel.Ip + " 信息：" + str);
                }
                else
                {
                    bool boolRes = Task.Factory.StartNew(() =>
                    {
                        while (!File.Exists(realPath))
                        {

                        }

                    }).Wait(3000);
                    if (!boolRes)
                    {
                        string resStr = "ip为" + this.cameraModel.Ip + "的摄像头，抓图失败，请检查网络问题！";
                        Common.Log4.LogManage.WriteErr(resStr);
                        reBaseModel.res = false;
                        DelegateHelper.InfoMessageEvent?.Invoke(resStr);
                    }
                }
            }
            else
            {
                CameraSdk.NET_DVR_JPEGPARA nET_DVR_JPEGPARA = new CameraSdk.NET_DVR_JPEGPARA();
                nET_DVR_JPEGPARA.wPicQuality = 1;
                nET_DVR_JPEGPARA.wPicSize = 3;
                if (!CameraSdk.NET_DVR_CaptureJPEGPicture(m_lUserID, mlChannel, ref nET_DVR_JPEGPARA, realPath))
                {
                    iLastErr = CameraSdk.NET_DVR_GetLastError();
                    str = "NET_DVR_CapturePicture failed, error code= " + iLastErr;
                    reBaseModel.res = false;
                }
                else
                {
                    bool boolRes = Task.Factory.StartNew(() =>
                    {
                        while (!File.Exists(realPath))
                        {

                        }

                    }).Wait(3000);
                    if (!boolRes)
                    {
                        string resStr = "ip为" + this.cameraModel.Ip + "的摄像头，抓图失败，请检查网络问题！";
                        Common.Log4.LogManage.WriteErr(resStr);
                        reBaseModel.res = false;
                        DelegateHelper.InfoMessageEvent?.Invoke(resStr);
                    }
                }
            }

            reBaseModel.Msg = realPath;
            return reBaseModel;
        }
        #endregion

        #region 道闸控制
        /// <summary>
        /// 道闸控制
        /// </summary>
        /// <param name="cmdFlag">
        /// 代码：1 开启道闸 0 关闭道闸 2停止道闸  3 锁定道闸
        /// </param>
        public bool BarrierGateControl(byte cmdFlag)
        {
            try
            {
                CameraSdk.NET_DVR_BARRIERGATE_CFG mStruControlCond = new CameraSdk.NET_DVR_BARRIERGATE_CFG();
                Int32 dwSize = Marshal.SizeOf(mStruControlCond);
                mStruControlCond.dwSize = (uint)dwSize;
                mStruControlCond.dwChannel = 1;
                mStruControlCond.byLaneNo = 1;
                mStruControlCond.byBarrierGateCtrl = cmdFlag;
                // mStruControlCond.byUnlock = 0;

                IntPtr ptrControlCfg = Marshal.AllocHGlobal(dwSize);
                Marshal.StructureToPtr(mStruControlCond, ptrControlCfg, false);

                if (!CameraSdk.NET_DVR_RemoteControl(m_lUserID, CameraSdk.NET_DVR_BARRIERGATE_CTRL, ptrControlCfg, (UInt32)dwSize))
                {
                    uint iLastErr = CameraSdk.NET_DVR_GetLastError();
                    LogManage.WriteErr("NET_DVR_BARRIERGATE_CTRL failed, error code= " + iLastErr);
                    return false;
                }
                Marshal.FreeHGlobal(ptrControlCfg);
            }
            catch (Exception ex)
            {
                LogManage.WriteErr("道闸控制 " + ex.ToString());
                return false;
            }
            return true;
        }

        #endregion

        #region 初始化登录打开摄像头一条龙
        /// <summary>
        /// 初始化登录打开摄像头一条龙
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public ReBaseModel ManualOne(object obj)
        {
            ReBaseModel reBaseModel = Init();
            if (!reBaseModel.res)
            {
                goto gt;
            }
            reBaseModel = Login();
            if (!reBaseModel.res)
            {
                goto gt;
            }
            if (obj != null)
            {
                reBaseModel = OpenorClose(obj);
                if (!reBaseModel.res)
                {
                    goto gt;
                }
            }
        gt:
            ;
            if (!reBaseModel.res)
            {
               // MessageBox.Show(reBaseModel.Msg);
                 Common.DelegateHelper.InfoMessageEvent?.Invoke("ManualOne失败 ip:" + cameraModel.Ip);
                  Common.Log4.LogManage.WriteErr("ManualOne失败 ip:" + cameraModel.Ip);
            }
            return reBaseModel;

        }

        #endregion

        private void RealDataCallBack(int lRealHandle, uint dwDataType, ref byte pBuffer, uint dwBufSize, IntPtr pUser)
        {
            //if (dwBufSize > 0)
            //{
            //    byte[] sData = new byte[dwBufSize];
            //    Marshal.Copy(pBuffer, sData, 0, (Int32)dwBufSize);

            //    string str = "实时流数据.ps";
            //    FileStream fs = new FileStream(str, FileMode.Create);
            //    int iLen = (int)dwBufSize;
            //    fs.Write(sData, 0, iLen);
            //    fs.Close();
            //}
        }
    }
}
